<template>
  <view class="page-index-format">
    <Loader ref="LoaderRef" />
    <Toast ref="ToastRef" />
    <QrPopup ref="QrPopupRef" />
    <OrderDetailPopup ref="OrderDetailPopup" />
    <Header text="订单"> </Header>
    <view class="container">
      <scroll-view
        v-if="showLists.length > 0"
        scroll-y
        class="scroll-view"
        :lower-threshold="80"
        :show-scrollbar="false"
        :scroll-top="scrolling.scrollTop"
        @scroll="handleScroll"
        @scrolltolower="handleLoadmore"
      >
        <view class="scroll-content">
          <view class="list" v-for="(item, index) in showLists" :key="index">
            <view class="format">
              <view class="top">
                <view class="left">
                  <view class="text mealCode">
                    <view class="reserve" v-if="item.orderType === 31">
                      {{ item.orderTypeDesc }}
                    </view>
                    <view class="label">取餐码：</view>
                    <view class="value">
                      {{ item.payStatus === 11 ? item.mealCode : "-" }}
                    </view>
                  </view>
                  <view class="text">
                    <view class="label">下单：</view>
                    <view class="value">{{ item.orderAt }}</view>
                  </view>
                  <view class="text" v-if="item.orderType === 31">
                    <view class="label">取餐：</view>
                    <view class="value">{{ item.expectAt }}</view>
                  </view>
                </view>
                <view class="right">
                  <view class="status">{{ item.payStatusDesc }}</view>
                  <view class="buyBaseInfo">
                    <template v-if="item.payStatus === 11 && item.walletAmount > 0">
                      <view class="text1-payAmount">￥{{ item.payAmount }}</view>
                      <view class="text1-totalAmount">￥{{ item.totalAmount }}</view>
                    </template>
                    <template v-else>
                      <view class="text2">￥{{ item.totalAmount }}</view>
                    </template>
                    <view class="num">x{{ item.goodsCount }}</view>
                  </view>
                </view>
              </view>
              <view class="bottom">
                <view class="btn detail">
                  <view class="format" @click="handleOpenDetail(item)"> 查看明细 </view>
                </view>
                <view class="btn" v-if="item.payStatus === 11">
                  <view class="format" @click="handleOpenQr(item)"> 取餐二维码 </view>
                </view>
                <view class="btn" v-if="item.payStatus === 10 && item.isToaday">
                  <view
                    class="format"
                    @click="handleOrder(item)"
                    style="background: #ffbd27"
                  >
                    重新支付
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="LoadMore">
          <view class="List" v-if="paging.loadingMore == 'warn'">- 加载中 -</view>
          <view class="List" v-else-if="paging.loadingMore == 'end'">- 加载完毕 -</view>
          <view
            class="List"
            v-else-if="paging.loadingMore == 'more'"
            @tap="handleLoadmore"
          >
            - 点击加载更多 -
          </view>
        </view>
      </scroll-view>
      <view class="empty-view" v-else>
        <view class="empty-content">
          <view class="bg"></view>
          <view class="text1">您今天还没有下单</view>
          <view class="text2">快去选择自己喜欢的美食吧</view>
          <view class="btn" @click="emit('tab', 'INDEX')">去点菜</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, nextTick, defineEmits, defineExpose, computed } from "vue";
import apiOrder from "@/api/order";
import store from "@/store/index";

const emit = defineEmits(["tab"]);
const LoaderRef = ref();
const ToastRef = ref();
const QrPopupRef = ref();
const OrderDetailPopup = ref();
const lists = ref([]);
const scrolling = reactive({
  scrollTop: 0,
  oldScrollTop: 0,
});
const paging = reactive({
  current: 1,
  size: 6,
  pages: 0, // 总分页
  loadingMore: "",
});
const showLists = computed(() => {
  const today = new Date().setHours(0, 0, 0, 0);
  const list = [];
  lists.value.forEach((item) => {
    let time = new Date(item.orderAt);
    if (time.getTime() > today) {
      item["isToaday"] = true;
    }
    list.push(item);
  });
  return list;
});

const handleScroll = (e) => {
  scrolling.oldScrollTop = e.detail.scrollTop;
};

const handleLoadmore = () => {
  if (paging.current >= paging.pages) {
    paging.loadingMore = "end";
  } else {
    paging.current++;
    hanldeList(false);
  }
};

const handleOpenDetail = (item) => {
  OrderDetailPopup.value.show(item);
};

const handleOpenQr = (item) => {
  QrPopupRef.value.show({
    title: item.mealCode,
    data: item.mealQrCode,
  });
};

const hanldeList = async (isRefresh = true) => {
  if (isRefresh) {
    paging.current = 1;
    if (lists.value.length > 0) {
      LoaderRef.value.show("更新订单中...");
    }
  }
  paging.loadingMore = "warn";
  try {
    let data = await apiOrder.page({
      size: paging.size,
      current: paging.current,
    });
    if (isRefresh) {
      lists.value = data.records;
      paging.pages = data.pages;
      scrolling.scrollTop = scrolling.oldScrollTop;
      await nextTick();
      scrolling.scrollTop = 0;
    } else {
      lists.value = lists.value.concat(data.records);
    }
    paging.loadingMore = paging.current >= paging.pages ? "end" : "more";
  } catch (err) {
    paging.loadingMore = "end";
  }
  LoaderRef.value.hide();
};

const payResult = async (type, data) => {
  switch (type) {
    case "success":
      ToastRef.value.show({
        title: "恭喜",
        content: "支付成功",
        onClose: async () => {
          try {
            LoaderRef.value.show("订单状态更新中");
            const res = await apiOrder.query({ id: data.id });
            store.isMember.value && (await store.updateWalletAmount());
            LoaderRef.value.hide(() => {
              data.payStatus = res.payStatus;
              data.payStatusDesc = res.payStatusDesc;
              handleOpenQr(res);
            });
          } catch (err) {
            LoaderRef.value.hide(() => {
              ToastRef.value.show({ title: "抱歉", content: err });
            });
          }
        },
      });
      break;
    case "fail":
      ToastRef.value.show({
        title: "抱歉",
        content: "支付失败",
        onClose: async () => {
          try {
            LoaderRef.value.show("订单状态更新中");
            await apiOrder.cancelPay({ id: data.id });
            const res = await apiOrder.query({ id: data.id });
            store.isMember.value && (await store.updateWalletAmount());
            LoaderRef.value.hide(() => {
              data.payStatus = res.payStatus;
              data.payStatusDesc = res.payStatusDesc;
            });
          } catch (err) {
            LoaderRef.value.hide(() => {
              ToastRef.value.show({ title: "抱歉", content: err });
            });
          }
        },
      });
      break;
  }
};
const handleOrder = async (item) => {
  try {
    LoaderRef.value.show("支付中");
    let walletAmount = 0;
    let payAmount = item.totalAmount;
    if (store.isMember.value) {
      await store.updateWalletAmount();
      if (store.state.walletAmount - item.totalAmount >= 0) {
        payAmount = 0;
        walletAmount = item.totalAmount;
      } else {
        payAmount = item.totalAmount - store.state.walletAmount;
        walletAmount = store.state.walletAmount;
      }
    }
    let data = await apiOrder.repay({
      orderId: item.id,
      payMethod: store.state.payMethod,
      walletAmount,
      payAmount: Math.round(payAmount * 100) / 100,
    });
    if (data.payStatus === 11) {
      LoaderRef.value.hide(() => {
        payResult("success", item);
      });
    } else {
      uni.requestPayment({
        nonceStr: data.extraMap.nonceStr,
        package: data.extraMap.package,
        paySign: data.extraMap.paySign,
        timeStamp: data.extraMap.timeStamp,
        signType: data.extraMap.signType,
        success: () => {
          LoaderRef.value.hide(() => {
            payResult("success", item);
          });
        },
        fail: () => {
          LoaderRef.value.hide(() => {
            payResult("fail", item);
          });
        },
      });
    }
  } catch (err) {
    LoaderRef.value.hide(() => {
      ToastRef.value.show({ title: "抱歉", content: err });
    });
  }
};

defineExpose({
  __onPageMounted: () => {},
  __onPageLoad: (opts) => {},
  __onPageLeave: () => {},
  __onPageShow: () => {},
  __onPageEnter: async () => {
    hanldeList();
  },
});
</script>
<style scoped lang="scss">
.page-index-format {
  position: relative;
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  & > .container {
    position: relative;
    flex: 1;
    overflow: hidden;
    height: 100%;
    background: #f1f8fa;
    border-top: solid 4rpx #f3f3f3;
    & > .scroll-view {
      position: relative;
      width: 100%;
      height: 100%;
      background: #f6f6f6;
      .scroll-content {
        position: relative;
        width: 100%;
        & > .list {
          position: relative;
          padding: 20rpx 20rpx 0 20rpx;
          box-sizing: border-box;
          &:last-child {
            padding-bottom: 20rpx;
          }
          & > .format {
            padding: 40rpx 25rpx;
            box-sizing: border-box;
            position: relative;
            width: 100%;
            display: flex;
            flex-direction: column;
            border-radius: 10px;
            background: #fff;
            & > .top {
              display: flex;
              & > .left {
                display: flex;
                flex-direction: column;
                flex: 1;
                width: 0;
                font-size: 24rpx;
                justify-content: space-between;
                & > .text {
                  display: flex;
                  align-items: center;
                  color: #5d656d;
                  & > .value {
                    flex: 1;
                    width: 0;
                  }
                }
                .mealCode {
                  font-size: 28rpx;
                  color: #333;
                  .reserve {
                    border-radius: 10rpx;
                    border: solid 2rpx #a5acb2;
                    padding: 8rpx 16rpx;
                    box-sizing: border-box;
                    margin-right: 20rpx;
                    line-height: 1;
                  }
                }
              }
              & > .right {
                display: flex;
                flex-direction: column;
                width: 150rpx;
                text-align: right;
                & > .status {
                  font-size: 28rpx;
                  color: #838484;
                  padding-bottom: 50rpx;
                }
                & > .buyBaseInfo {
                  color: #635b5d;
                  line-height: 1.2;
                  font-size: 24rpx;
                  .text2,
                  .text1-payAmount {
                    font-size: 28rpx;
                    color: #e73b29;
                  }
                  .text1-totalAmount {
                    font-size: 24rpx;
                    color: #333;
                    text-decoration: line-through;
                  }
                  .num {
                    font-size: 20rpx;
                    padding-top: 10rpx;
                  }
                }
              }
            }
            & > .bottom {
              display: flex;
              justify-content: flex-end;

              .btn {
                padding-top: 30rpx;
                margin-left: 20rpx;
                &.detail .format {
                  background: #a5acb2;
                }
                .format {
                  font-size: 24rpx;
                  padding: 15rpx 25rpx;
                  border-radius: 10rpx;
                  background: var(--Main_Color);
                  color: #fff;
                }
              }
            }
          }
        }
      }
    }
    & > .empty-view {
      position: relative;
      width: 100%;
      height: 100%;
      display: flex;
      justify-items: center;
      align-items: center;
      & > .empty-content {
        position: relative;
        width: 100%;
        display: flex;
        flex-direction: column;
        justify-items: center;
        align-items: center;
      }
      .bg {
        background-image: var(--Img_Order_Gif);
        background-size: auto 100%;
        background-position: center center;
        background-repeat: no-repeat;
        height: 300rpx;
        width: 200rpx;
        margin-bottom: 40rpx;
      }
      .text1,
      .text2 {
        position: relative;
        font-size: 28rpx;
        color: #8a8a8b;
        line-height: 1;
        margin-bottom: 15rpx;
      }
      .btn {
        width: 50%;
        margin-top: 60rpx;
        line-height: 1;
        padding: 25rpx 0;
        font-size: 30rpx;
        border-radius: 10rpx;
        text-align: center;
        background: var(--Main_Color);
        color: #fff;
      }
    }
  }
}
</style>
